<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\madmin\service;

use app\index\service\QrcodeService;
use app\madmin\model\Advert;
use app\madmin\model\Commodity;
use app\madmin\model\Mytemplate;
use app\madmin\model\Renovation;
use app\madmin\model\Template;
use app\madmin\model\TemplateClassify;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class PageService
{
    public $merchantId;

    const url_arr = [1 => "pages/index/index", 2 => "pages/detail/detail", 3 => "pages/mine/mine", 4 => "pages/custompage/custompage"];

    public function __construct()
    {
        global $user;
        $this->merchantId = $user->merchant_id;
    }

    /**页面装修列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function pageList(array $data)
    {
        $res = Renovation::where($this->bulidWhere($data))
            ->alias('a')
            ->order('a.status desc')
            ->field('a.page_name,a.page_type,a.status,a.small_img,a.update_time,a.id,a.source,a.create_time')
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']]);
        return [HTTP_SUCCESS, $res];
    }

    /**创建页面装修
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createPage(array $data)
    {
        $page_config = $data['page_config'];
        unset($data['page_config']);
        //每个类型只有一个页面激活
        if (in_array($data['page_type'], [1, 2, 3]) && $data['status'] == 2) {
            Renovation::where('page_type', $data['page_type'])
                ->whereRaw('source REGEXP "[' . $data['source'] . ']"')
                ->where('merchant_id', $this->merchantId)
                ->update(['status' => 1]);
        }
        $find = Renovation::where('page_name', $data['page_name'])->find();
        if ($find) throw new HttpException(HTTP_INVALID, "页面名称不能重复");
        $data['merchant_id'] = $this->merchantId;
        $data['page_config'] = json_encode($page_config, true);
        $create = Renovation::create($data);
        return [HTTP_SUCCESS, $create];
    }

    /**删除装修接口
     * @param int $id
     * @return int
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function delPage(int $id)
    {
        $find = Renovation::find($id);
        if ($find['status'] == 2) throw new HttpException(HTTP_INVALID, "应用中不可被删除");
        Renovation::destroy($id);
        return HTTP_NOCONTEND;
    }

    /**二维码-预览
     * @param int $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function preview(int $id)
    {


        $user_type = \request()->get('user_type',3);

        global $user;
        $find = Renovation::find($id);
        $base_url = Request::domain() . "/h5/#/";
        $lj = self::url_arr[$find['page_type']];
        $find['page_type'] == 2 ? $sid = Commodity::where('status', 1)->order('id desc')->field('id')->find() : $sid['id'] = $id;

//        $user_type = 1;
        if ($user_type == 1) {
            //todo 微信小程序
            global $baseIn;
            global $user;
            global $m_id;
            $m_id = $user->mall_id;
            $baseIn = "wechata";
            $path = "";
//            $page="pages/index/index"; #首页
//            $page="pages/mine/mine"; #个人中心
            $scene = "id={$sid['id']};mall_id={$m_id}";
            try {
                $service = new QrcodeService();
                list($code, $msg) = $service->qrcode($path, "", $scene, $lj);
                $data['link'] = \request()->domain() . $msg;
            } catch (\Exception $e) {
                return [HTTP_NOTACCEPT, $e->getMessage()];
            }

        } else {
            $str = $base_url . $lj . "?id=" . $sid['id'] . "&mall_id=" . $user->mall_id;
            $data = [
                'link' => $str
            ];
        }


        return [HTTP_SUCCESS, $data];
    }

    /**获取装修配置详情
     * @param int $id
     * @return array
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function renovation(int $id)
    {
        $find = Renovation::find($id);
        $find['configure'] = str_replace("\n", " ", $find['configure']);
        return [HTTP_SUCCESS, $find];
    }

    /** 生成二维码
     * @param $merchant_id
     * @param $page_type
     * @param $pid
     * @return string
     */
    private function make_qrcode($merchant_id, $page_type, $pid)
    {
        $base_url = Request::domain() . "/h5/#/";
        $lj = $merchant_id == 1 ? self::url_arr[$page_type] : "pages/custompage/custompage";
        $str = $base_url . $lj . "?pid=" . $pid;
        $path = qrcode($str);
        return $path;
    }

    /**获取自己模板
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function myTemplate(array $data)
    {
        $tems = Mytemplate::where('merchant_id', $this->merchantId)
            ->where('page_type', $data['type'])
            ->field('id,page_name,page_type,small_img,create_time,source')
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']]);
        return [HTTP_SUCCESS, $tems];
    }

    /**我的模板保存
     * @param array $data
     * @return array
     */
    public function saveMyTemplate(array $data)
    {
        global $user;
        $page_config = $data['page_config'];
        $id = $data['id'];
        unset($data['page_config'], $data['id']);
        $data['merchant_id'] = $this->merchantId;
        $data['mall_id'] = $user['mall_id'];
        if (!empty($page_config)) $data['page_config'] = json_encode($page_config, true);
        $create = Mytemplate::update($data, ['id' => $id], ['page_config', 'page_name', 'page_type', 'small_img', 'source', 'mall_id', 'configure']);
        return [HTTP_SUCCESS, $create];
    }

    /**
     * 更新装修数据
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function upRenovation(array $data)
    {
        $id = $data['id'];
        $page_config = $data['page_config'];
        unset($data['page_config'], $data['id']);
        $data['page_config'] = json_encode($page_config, true);
        $str = 'TEMPLATE::' . $id;
        $data['page_key'] = $str;
        $find = Renovation::where('page_name', $data['page_name'])->where('id', '<>', $id)->find();
        if ($find) throw new HttpException(HTTP_INVALID, "页面名称不能重复");
        if (in_array($data['page_type'], [1, 2, 3]) && $data['status'] == 2) {
            Renovation::where('page_type', $data['page_type'])
                ->whereRaw('source REGEXP "[' . $data['source'] . ']"')
                ->where('merchant_id', $this->merchantId)
                ->update(['status' => 1]);
        }
        $up = Renovation::update($data, ['id' => $id]);

        return [HTTP_SUCCESS, $up];
    }

    /**保存为模板
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveTemplate(array $data)
    {
        $find = Mytemplate::where('page_name', $data['page_name'])->find();
        if ($find) throw new HttpException(HTTP_INVALID, "页面名称不能重复!");
        $page_config = $data['page_config'];
        unset($data['page_config']);
        $data['merchant_id'] = $this->merchantId;
        $data['page_config'] = json_encode($page_config, true);
        $create = Mytemplate::create($data);
        return [HTTP_SUCCESS, $create];
    }

    /** 获取公用模板
     * @param int $id
     * @return array
     */
    public function getTemplateInfo(int $id)
    {
        $find = Template::find($id);
        $find['configure'] = str_replace("\n", " ", $find['configure']);
        return [HTTP_SUCCESS, $find];
    }

    /**
     * 模板市场
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function market(array $data)
    {
        $res = Template::field('page_name,page_type,small_img,id,source,class_name')
            ->where($this->setWhere($data))
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']]);
        return [HTTP_SUCCESS, $res];
    }

    /**
     * 我的模板列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function myTemplateList(array $data)
    {
        $res = Mytemplate::where($this->setWhere($data))
            ->field('page_name,page_type,small_img,id,source,class_name')
            ->order('id', 'desc')
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']]);
        return [HTTP_SUCCESS, $res];
    }

    /**获取我的模板详情
     * @param int $id
     * @return array
     */
    public function getMyTemplateInfo(int $id)
    {
        $data = Mytemplate::find($id);
        $res['configure'] = $data['configure'];
        return [HTTP_SUCCESS, $res];
    }

    /**删除我的模板
     * @param int $id
     * @return int
     */
    public function delMytemplate(int $id)
    {
        Mytemplate::destroy($id);
        return HTTP_NOCONTEND;
    }

    /**创建公有模板
     * @param array $data
     * @return array
     */
    public function createPublicTemplate(array $data)
    {
        $page_config = $data['page_config'];
        unset($data['page_config']);
        $data['page_config'] = json_encode($page_config, true);
        $create = Template::create($data);
        return [HTTP_SUCCESS, $create];
    }

    /**开启
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function enable(array $data)
    {
        $find = Renovation::find($data['id']);
        if (in_array($find['page_type'], [1, 2, 3]) && $data['status'] == 2) {
            Renovation::where('page_type', $find['page_type'])
                ->whereRaw('source REGEXP "[' . $find['source'] . ']"')
                ->where('merchant_id', $this->merchantId)
                ->update(['status' => 1]);
        }
        $up = Renovation::update(['status' => $data['status']], ['id' => $data['id']]);
        return [HTTP_SUCCESS, $up];
    }

    /** 修改来源
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveSource(array $data)
    {
        foreach ($data as $v) {
            foreach ($v as $vv) {
                if (empty($vv['source'])) throw new HttpException(HTTP_INVALID, "渠道不能为空!");
                $find = Renovation::find($vv['id']);
                $find->source = trim($vv['source'], ',');
                $find->save();
                if (in_array($find['page_type'], [1, 2, 3]) && $find['status'] == 2) {
                    Renovation::where('page_type', $find['page_type'])
                        ->whereRaw('source REGEXP "[' . $find['source'] . ']"')
                        ->where('merchant_id', $this->merchantId)
                        ->where('id', '<>', $find['id'])
                        ->update(['status' => 1]);
                }
            }
        }
        return [HTTP_SUCCESS, '成功!'];
    }

    /**启动广告
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function startAdvert(array $data)
    {
        global $user;
        $content = json_encode($data['content'], true);
        unset($data['content']);
        $data['content'] = $content;
        if (!array_key_exists('id', $data)) {
            $find = Advert::where('mall_id', $user->mall_id)->find();
            if ($find) throw new Exception('该商城已有启动广告!', HTTP_INVALID);
            $data['mall_id'] = $user->mall_id;
            $up = Advert::create($data);
        } else {
            $id = $data['id'];
            unset($data['id']);
            $up = Advert::update($data, ['id' => $id]);
        }
        return [HTTP_SUCCESS, $up];
    }

    /**
     *查询
     */
    public function advert()
    {
        global $user;
        $find = Advert::where('mall_id', $user->mall_id)->find();
        $find['content'] = json_decode($find['content'], true);
        return [HTTP_SUCCESS, $find];
    }

    /**我的分类
     * @param int $page
     * @param int $size
     * @return array
     * @throws DbException
     */
    public function classList(int $page, int $size)
    {
        $res = TemplateClassify::order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $res];
    }

    private function bulidWhere(array $data)
    {
        $where = [];
        !empty($data['page_name']) && $where[] = ['a.page_name', 'like', "%" . $data['page_name'] . "%"];
        !empty($data['status']) && $where[] = ['a.status', '=', $data['status']];
        !empty($data['page_type']) && $where[] = ['a.page_type', '=', $data['page_type']];
        !empty($data['merchant_id']) && $where[] = ['a.merchant_id', '=', $this->merchantId];
        return $where;
    }

    private function setWhere($data)
    {
        $where = [];
        if (!$data['page_type']) $where[] = ['page_name', 'NOT IN', ['个人中心V1', '商品详情V1']];
        !empty($data['page_type']) && $where[] = ['page_type', '=', $data['page_type']];
        !empty($data['class_name']) && $where[] = ['class_name', '=', $data['class_name']];
        !empty($data['page_name']) && $where[] = ['page_name', 'like', $data['page_name'] . "%"];
        return $where;
    }

    public function defaultTemplate()
    {
        $res = Renovation::where('mall_id', 4236)
            ->hidden(['create_time,update_time,delete_time', 'id'])
            ->where('page_name', 'IN', ['个人中心V1', '商品详情V1', '迪丽热巴'])
            ->select()
            ->toArray();
        foreach ($res as $k => $v) {
            $res[$k]['configure'] = Cache::get($v['page_key']);
            unset($res[$k]['page_key']);
            $id = Db::name('default_template')->insertGetId($res[$k]);
            Db::name('default_template')->where('id', $id)->update(['page_key' => "TEMPLATE::" . $id]);
        }
    }

    public function setDefaultTemplate()
    {
        $res = Db::name('default_template')->select();
        foreach ($res as $v) {
            $id = Template::insertGetId(['page_name' => $v['page_name'],
                'page_type' => $v['page_type'],
                'small_img' => $v['small_img'],
                'page_config' => $v['page_config'],
                'source' => $v['source'],
                'class_name' => $v['class_name'] ?? null]);
            $str = "PUBLIC_TEMPLATE::" . $id;
            Cache::set($str, $v, 0);
            Db::name('template')->where(['id' => $id])->update(['page_key' => $str]);
        }

        return [HTTP_SUCCESS, '成功'];
    }

    public function text()
    {
        $res = Db::name('renovation')->select();
        foreach ($res as $v) {
            $configure = Cache::get($v['page_key']);
            Db::name('renovation')->where(['id' => $v['id']])->update(['configure' => $configure['configure']]);
        }
        return [HTTP_SUCCESS, '成功'];
    }


}